#!/bin/bash

# ========== 配置区域 ==========
# Packagist 用户名
USERNAME="note-sun"

# Packagist API Token（可以使用 main 或 safe token）
API_TOKEN="2f505bdf02ab950c93ffcbcffb4b5ee69a2ae785"

# 仓库地址（可以是 GitHub 仓库地址或 Packagist 包地址）
REPO_URL="https://packagist.org/packages/sunadmin/template"

# ========== 获取最新git标签（版本号） ==========
LATEST_TAG=$(git tag --list --sort=-v:refname | head -n 1)
echo "当前最新版本号: $LATEST_TAG"

# ========== 询问新版本号 ==========
echo "请输入新版本号（直接回车将自动递增patch，或手动输入新版本号）："
read INPUT_VERSION

# 递增patch逻辑
if [ -z "$INPUT_VERSION" ]; then
  if [[ $LATEST_TAG =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
    MAJOR=${BASH_REMATCH[1]}
    MINOR=${BASH_REMATCH[2]}
    PATCH=${BASH_REMATCH[3]}
    PATCH=$((PATCH+1))
    NEW_VERSION="$MAJOR.$MINOR.$PATCH"
  else
    echo "未检测到标准版本号，需手动输入新版本号："
    read NEW_VERSION
  fi
else
  NEW_VERSION="$INPUT_VERSION"
fi

echo "新版本号: $NEW_VERSION"

# ========== 询问是否写入composer.json ==========
COMPOSER_JSON="$(dirname "$0")/composer.json"
if [ -f "$COMPOSER_JSON" ]; then
  echo "是否将新版本号写入 composer.json? (y/N): "
  read WRITE_COMPOSER
  if [[ "$WRITE_COMPOSER" =~ ^[Yy]$ ]]; then
    if command -v jq &> /dev/null; then
      TMPFILE=$(mktemp)
      jq --arg v "$NEW_VERSION" '.version = $v' "$COMPOSER_JSON" > "$TMPFILE" && mv "$TMPFILE" "$COMPOSER_JSON"
      echo "已写入 composer.json version 字段: $NEW_VERSION"
    else
      echo "未安装 jq，无法自动写入 composer.json，请手动维护 version 字段。"
    fi
  fi
fi

# ========== Git 操作 ==========
echo "💾 提交所有更改到git..."
git add .
echo "请输入本次发布的 commit message（如 feat: 新增xx/修复xx/发布v$NEW_VERSION 等，直接回车则使用版本号）:"
read COMMIT_MSG
if [ -z "$COMMIT_MSG" ]; then
  COMMIT_MSG="release: v$NEW_VERSION"
fi
git commit -m "$COMMIT_MSG" || echo "（无变更可提交）"
echo "🏷️ 打标签: v$NEW_VERSION"
git tag -a "$NEW_VERSION" -m "$COMMIT_MSG" || echo "（标签已存在）"
echo "🚀 推送代码和标签到远程仓库..."
git push || true
git push --tags || true

# ========== 执行请求 ==========
API_URL="https://packagist.org/api/update-package?username=${USERNAME}&apiToken=${API_TOKEN}"

echo "正在更新packagist包: $REPO_URL"

curl -X POST -H "Content-Type: application/json" \
     -d "{\"repository\":\"$REPO_URL\"}" \
     "$API_URL"
